**********************************************************
*	Is Extreme Ideology a threat for Liberal Democray    *
*														 *
*	Created: 13/09/2023									 *
*	LUpdate: 14/10/2024									 *
**********************************************************

**********************************************************
** SETTINGS												**
**********************************************************
/*DESKTOP
cd "C:\Users\57313\Dropbox\ProyectosJavier\"
LAPTOP
cd "C:\Users\jssal\Dropbox\ProyectosJavier\"
*/

		*****************************************************
		 ***************************************************
		  **********#	SUPPLEMENTAL DATASETS	#**********
		 ***************************************************
		*****************************************************

*** COMP. DS 1: WORLD BANK UNCOME AND REGION 2021-2022
**********************************************************
use "Process/WBIncomeRegion2021_2022.dta", replace
replace ISO3="CPV" if country=="Cabo Verde"
replace ISO3="SRB" if country=="Serbia"
replace ISO3="COD" if country=="Congo, Dem. Rep."
drop if ISO3==""
replace ISO3=trim(ISO3)
replace ISO3=itrim(ISO3)
replace ISO3=ustrtrim(ISO3)
save WBINC, replace 
*** COMP. DS 2: Reinhart & Rogoff Crisis data 1990-2016
**********************************************************
import excel "RR_global_crisis_data.xlsx", sheet("Sheet1") firstrow clear
drop if _n==1
keep if Year>1990
drop nationalcurrency exch_primarysourcecode exch_sources GDP_Weighted_default W Independence
rename Year year
rename Country country
foreach var of var BankingCrisis SystemicCrisis GoldStandard exch_usd exch_usd_alt1 exch_usd_alt2 exch_usd_alt3 Domestic_Debt_In_Default SOVEREIGNEXTERNALDEBT1DEFAU SOVEREIGNEXTERNALDEBT2DEFAU InflationAnnualpercentagesof CurrencyCrises InflationCrises {
replace `var'="." if `var'=="n/a"
destring `var', replace
}
rename CC3 ISO3
replace ISO3=trim(ISO3)
replace ISO3=itrim(ISO3)
replace ISO3=ustrtrim(ISO3)
save RR_GC, replace
*** COMP. DS 3: WDI World Bank
**********************************************************
import excel "C:\Users\57313\Dropbox\Javier Corrales\P_Data_Extract_From_World_Development_Indicators.xlsx", sheet("Data") firstrow clear
rename Time year
rename CountryName country
foreach var of var Populationlivinginslumsof	Populationdensitypeoplepers	Peopleusingatleastbasicdrin	Inflationconsumerpricesannu	GDPconstant2015USNYGDP	Centralgovernmentdebttotal	Unemploymenttotaloftotal	HumancapitalindexHCImale	Incomeshareheldbyhighest10	GDPpercapitaconstant2015US {
replace `var'="." if `var'==".."
destring `var', replace
} 
rename CountryCode ISO3
replace ISO3=trim(ISO3)
replace ISO3=itrim(ISO3)
replace ISO3=ustrtrim(ISO3)
drop if ISO3=="" & year==. 
save WDI, replace
*** COMP. DS 4: DEED
**********************************************************
import excel "C:\Users\jssal\Dropbox\ProyectosJavier\OriginalDatasets\DEED_v6_final.xlsx", sheet("DEED_ACE_v6_Fall 2023") firstrow clear
rename Country country
gen uno=1
*tab EventCategory
gen RedHor_Account=0
replace RedHor_Account=1 if inlist(EventCategory,"Reduction in judicial independence","Reduction in legislative oversight", "Weakened civil service or integrity institutions", "Suspension of laws or the constitution", "Relaxation of term limits", "Revision of the constitution", "Reduction autonomy of subnational units")
gen RedVer_Account=0
replace RedVer_Account=1 if inlist(EventCategory,"Repression of the opposition", "Systemic reduction in election freedom and fairness", "Curtailed civil liberties", "Media repression", "No-confidence votes or decreased voter turnout", "Foreign military action" , "Discrimination against minorities")
keep if RedHor_Account==1 | RedVer_Account==1 // | Extremism==1 | Polarization==1
gen RedHor_Account_w=RedHor_Account*CoderRating
gen RedVer_Account_w=RedVer_Account*CoderRating
collapse (sum) symptoms=uno RHor=RedHor_Account RVer=RedVer_Account (mean) RHsymp_w=RedHor_Account_w RVsymp_w=RedVer_Account_w, by(country Year_1)
rename Year_1 year
rename country country_name
keep if year<2023
replace country_name="Palestine/West Bank" if country_name=="Palestine"
replace country_name="North Macedonia" if country_name=="Macedonia" 
replace country_name="Czechia" if country_name=="Czech Republic" 
save DEED, replace

		*****************************************************
		 ***************************************************
		  **********#		MAIN DATASET		#**********
		 ***************************************************
		*****************************************************

*** MERGING DS 1
******************************************************
*use "DB_LibDemIdeology.dta", clear
* drop t yhatc
use "OriginalDatasets/V-Dem-CY-Full+Others-v13.dta", clear
 keep if year>1990 
codebook v2x_libdem v2exl_legitideol_osp  v2exl_legitideol
 rename (v2x_libdem v2exl_legitideol_ord v2exl_legitideol) (libdemind idologysco idologyint)
sort country_id year 
*br country_name country_id year libdemind idologysco idologyint
gen dlb =(libdemind -libdemind[_n-1]) 	if country_id==country_id[_n-1]
gen din =(idologyint -idologyint[_n-1]) if country_id==country_id[_n-1]
gen din4=(idologyint -idologyint[_n-4]) if country_id==country_id[_n-4]
gen dis =(idologysco -idologysco[_n-1]) if country_id==country_id[_n-1]
gen dis4=(idologysco -idologysco[_n-4]) if country_id==country_id[_n-4]
** One treatment variable for the graphs
gen IdeoChange=0 // Increase of more than one unit in ideology in a single year 
 replace IdeoChange=1 if din>=1 
 replace IdeoChange=2 if din4>=2
 replace IdeoChange=3 if din>=1.335266 
 replace IdeoChange=4 if din>=2.1965126
 replace IdeoChange=5 if din>=2.6171214
** Treatment variables
gen Treatment_1=(din>=1 		 & din!=.) 
gen Treatment_2=(din>=1.335266   & din!=.) 
*gen Treatment_3=(din>=2.1965126  & din!=.) 
*gen Treatment_4=(din>=2.6171214  & din!=.) 
gen Treatment_11=(din4>=2 		 & din4!=.) 
gen Treatment_12=(din4>=2.670532 & din4!=.) 
 label var Treatment_1  "Increase of one unit or more in ideology score in a single year"
 label var Treatment_2  "Increase of one std. dev or more in ideology score in a single year"
 *label var Treatment_3  "Increase of 1.64 std. dev or more in ideology score in a single year"
 *label var Treatment_4  "Increase of 1.96 std. dev more in ideology score in a single year"
 label var Treatment_11 "Increase of more than two units in ideology score in a four years period"
 label var Treatment_12 "Increase of more than two std. dev in ideology score in a four years period"
*Dates for the Event Study  
gen EventDate_1=year  if Treatment_1==1
gen EventDate_2=year  if Treatment_2==1 
gen EventDate_11=year if Treatment_11==1 
gen EventDate_12=year if Treatment_12==1 
 label var Treatment_1  "Date of increase of one unit or more in ideology score in a year"
 label var Treatment_2  "Date of increase of one std. dev or more in ideology score in a year"
 label var Treatment_11 "Date of increase of more than two units in ideology score in four years"
 label var Treatment_12 "Date of increase of more than two std. dev in ideology score in four years"
*Including the reduced dataset
merge m:1 country_name using "Process/reduced_list.dta", nogen
replace relevant_cases=0 if relevant_cases==.
rename country_text_id ISO3
merge m:1 ISO3 using "Process/WBINC.dta", gen(WB)
 drop if WB==2
  replace region="Latin America & Caribbean" if ISO3=="VEN"
   drop WB
bysort country_id: egen country_treat=max(Treatment_1) 
encode incomegroup, gen(INCOME)
encode region, gen(REGION)
*** MERGING DS 2
******************************************************
merge 1:1 ISO3 year using "Process\RR_GC.dta", gen(RR)
*tab country RR if RR<3 & year<2017
tab country year if RR==1
 drop if RR==2
  drop RR  
*** MERGING DS 3
******************************************************
merge 1:1 ISO3 year using "Process\WDI.dta", gen(WDI)
*tab country RR if RR<3 & year<2017
 drop if WDI==2
  drop WDI
save "Process\VDEM_Expanded_DB.dta", replace


		*****************************************************
		 ***************************************************
		  **********#		FIGURES				#**********
		 ***************************************************
		*****************************************************

*** FIGURE 1 
******************************************************
use "Process\VDEM_Expanded_DB.dta", replace
bysort country_id: gen n=_N
drop if n<32
sort country_id year
*colorpalette viridis, n(7) 
grstyle init
grstyle set color viridis, n(7) select(1 4 6): 
grstyle set color viridis, n(7) select(1 4 6): p#markfill p#markline  p#lineplot  
* Figure only for the PPT
su idologyint year
twoway (scatter idologyint year, msym(d) msize(*.4) mcolor(%75)) || (line idologyint year if ISO3=="USA", lwidth(*2)) || (line idologyint year if ISO3=="VEN", lwidth(*2)) if year<2020, xlab(1990(2)2020) ///
  legend(pos(6) row(1) label(1 "Ideology Score of each Country") label(2 "USA") label(3 "VEN")) ///
  ylab(-3.0 "No Use of" -3.25 "Ideology " 3.5 " Almost   " 3.25 "Exclusively" 3 "use of    " 2.75"Ideology ", notick nogrid) ///
  ytitle("") ysca(r(-3.4 3.6) lstyle(none)) ///
  text(4 1998 "{bf:Chávez was elected}", color("143 215 68")) ///
  text(4 2016 "{bf:Trump was elected}", color("33 144 140")) ///
  xline(1998, lsty(continuous) lwidth(*6) lcolor("143 215 68")) ///
  xline(2016, lsty(continuous) lwidth(*6) lcolor("33 144 140")) 
graph export "Results\Fig1.png", as(png) name("Graph") width(2000) replace  
tab year
*** FIGURE 2
******************************************************
use "Process\VDEM_Expanded_DB.dta", replace
bysort country_id: gen n=_N
drop if n<32
grstyle init 
gen  libdemind100=libdemind *100 
 grstyle set color viridis, n(7):
*A negative relation, but it is a cloud of dots, full sample
splitvallabels idologysco, length(20) recode
*vioplot libdemind, over(idologysco) b1title("Ideology", size(*.8))
graph box libdemind100, over(idologysco, relabel(`r(relabel)')) ///
ytitle(Liberal Democracy Index, size(medlarge)) b1title("Ideology", size(medlarge))
graph export "Results\Fig2.png", as(png) name("Graph") width(2000) replace  
  
*** FIGURE 3
******************************************************
use "Process\VDEM_Expanded_DB.dta", replace
bysort country_id: egen first_ideoshock_1= min(EventDate_1)
bysort country_id: egen first_ideoshock_2= min(EventDate_2)
gen ry1 = year - first_ideoshock_1
gen never_ideoshock_1 = (first_ideoshock_1== .)
tab ry1
gen  libdemind100=libdemind *100 
keep libdemind100 ry1 never_ideoshock_1 country_name first_ideoshock_1
*We keep only the countries with ideological shocks
keep if never_ideoshock_1==0
keep if ry1==-2 | ry1==2
gen a_sh=(ry1==2)
*tab a_sh ry1
drop ry1
reshape wide libdemind100, i(country_name) j(a_sh)
keep if libdemind1001!=.
drop if country_name=="Palestine/West Bank"
gen diff_libdemind=libdemind1001-libdemind1000
tostring first_ideoshock_1, replace
gen co_y = country_name + ", " + first_ideoshock_1

graph hbar diff_libdemind, over(co_y, sort(diff_libdemind) label(labsize(small))) ///
 ytitle("Changes on the Liberal democracy" "index 2yrs before and after ideologization") ///
 ysize(*1.5) xsize(*1.1)
graph export "Results\Fig3.png", as(png) name("Graph") width(2000) replace  

/* Figure 3. (using 5 years instead)
use "Process\VDEM_Expanded_DB.dta", replace
bysort country_id: egen first_ideoshock_1= min(EventDate_1)
bysort country_id: egen first_ideoshock_2= min(EventDate_2)
gen ry1 = year - first_ideoshock_1
gen never_ideoshock_1 = (first_ideoshock_1== .)
tab ry1
gen  libdemind100=libdemind *100 
keep libdemind100 ry1 never_ideoshock_1 country_name first_ideoshock_1
*We keep only the countries with ideological shocks
keep if never_ideoshock_1==0
keep if ry1==-2 | ry1==5
gen a_sh=(ry1==5)
*tab a_sh ry1
drop ry1
reshape wide libdemind100, i(country_name) j(a_sh)
keep if libdemind1001!=.
drop if country_name=="Palestine/West Bank"
gen diff_libdemind=libdemind1001-libdemind1000
tostring first_ideoshock_1, replace
gen co_y = country_name + ", " + first_ideoshock_1
graph hbar diff_libdemind if diff_libdemind!=., over(co_y, sort(diff_libdemind)) ytitle("Changes on the Liberal democracy index 2yrs before and 5yrs after ideologization") 
*/

*** Changes in lib  democracy
******************************************************
use "Process\VDEM_Expanded_DB.dta", replace
gen ReducedLD=(dlb<-0.1)
gen LDDate=year if ReducedLD==1
bysort country_id: egen LDshock_1= min(LDDate)
gen ry1 = year - LDshock_1
gen never_libshock = (LDshock_1== .)
tab ry1
gen  libdemind100=libdemind *100 
keep idologyint ry1 never_libshock LDshock_1 country_name LDshock_1
keep if never_libshock ==0
keep if ry1==-2 | ry1==2
gen a_sh=(ry1==2)
drop ry1
reshape wide idologyint, i(country_name) j(a_sh)
keep if idologyint1!=.
drop if country_name=="Palestine/West Bank"
gen diff_ideology=idologyint1-idologyint0
keep if diff_ideology!=.
tostring LDshock_1, replace
gen co_y = country_name + ", " + LDshock_1
graph hbar diff_ideology, over(co_y, sort(diff_ideology)) ytitle("Changes on Ideologization Score 2yrs before and after a change on the LD Index") 



*** EVENT STUDY 
******************************************************
use "Process\VDEM_Expanded_DB.dta", replace
bysort country_id: gen n=_N
drop if n<32
*Per every country
*br year country_id EventDate_1
bysort country_id: egen first_ideoshock_1= min(EventDate_1)
bysort country_id: egen first_ideoshock_2= min(EventDate_2)
*In case we want to filter the countries with recent shocks
*drop if first_ideoshock_1>2018 & first_ideoshock_1<2023
gen ry1 = year - first_ideoshock_1
gen never_ideoshock_1 = (first_ideoshock_1== .)
tab ry1
keep libdemind first_ideoshock_1 ry1 never_ideoshock_1 country_id year e_regionpol PopulationtotalSPPOPTOTL GDPpercapitaconstant2015US Populationdensitypeoplepers e_cow_exports e_cow_imports e_miinflat e_total_resources_income_pc e_pt_coup_attempts e_civil_war e_democracy_trans BankingCrisis CurrencyCrises InflationCrises v2peedueq e_peaveduc
        forvalues k = 10(-1)2 {
           gen g_`k' = ry1 == -`k'
        }
        forvalues k = 0/10 {
             gen g`k' = ry1 == `k'
        }
gen libdemind100=100*libdemind		
tab never_ideoshock_1, sum(libdemind100 )
*************************
* Controlling by region *
*************************
keep if e_democracy_trans!=. & e_pt_coup_attempts!=. & v2peedueq!=. 
keep if PopulationtotalSPPOPTOTL!=. & GDPpercapitaconstant2015US!=. & Populationdensitypeoplepers!=.
local region "e_regionpol"
eventstudyinteract libdemind100 g_* g0-g10, cohort(first_ideoshock_1) control_cohort(never_ideoshock_1) covariates(`region') absorb(i.country_id i.year) vce(cluster e_regionpol) 
*outreg2 using mat.xlsx, excel replace
* We want the weighted coeficients
matrix B1 = e(b_iw)
matrix list B1
* Now we need to add the SE
mata st_matrix("A1",sqrt(diagonal(st_matrix("e(V_iw)"))))
matrix W1 = B1 \ A1'
matrix list W1
matrix rownames W1 = b se
* We need to create a matrix with the SE
matrix SE1 = W1["se",.]
matrix list SE1
*We add to our estored estimations the coeficients and the SE
estadd matrix B1
estadd matrix SE1
*We add a few 
estout using "Results\ES.xls", replace  cells(B1(fmt(5)) SE1(par fmt(3)))
grstyle init 
 grstyle set color viridis, n(7) select(1):
 grstyle set color viridis, n(7) select(1): p#line p#bar p#fill
coefplot matrix(B1), se(SE1) keep(g*) vertical recast(line) note("{bf: Covariates}: Geopolitical region" "{bf: Number of obs}: 4,758") ///
levels(95 90) ciopts(lwidth(2.5 ..) lcolor(*.5 *.8)) ///
yline(0) ytitle(Effect on Liberal Democracy Index) ///
xline(9.5, lcolor(black) lpattern(solid))  xtitle(Years From the First Ideology Shock) ///
	coeflabels(g_10 = "-10" g_9 = "-9" g_8 = "-8" g_7 = "-7" g_6 = "-6" ///
				g_5 = "-5" g_4 = "-4" g_3 = "-3" g_2 = "-2" g_1 = "-1" ///
				g10 = "10" g9 = "9" g8 = "8" g7 = "7" g6 = "6" ///
				g5 = "5"   g4 = "4" g3 = "3" g2 = "2" g1 = "1" g0 = "0" )			
graph export "Results\ES_RE.png", as(png) name("Graph") width(2000) replace
putexcel set "Results\ES_RE.xlsx", replace
putexcel a2="b1"
putexcel a3="se1"
putexcel b1=matrix(W1), colnames 

**Figure 4**
* Region Pop GDP
local demecon "e_regionpol PopulationtotalSPPOPTOTL GDPpercapitaconstant2015US Populationdensitypeoplepers"
eventstudyinteract libdemind100 g_* g0-g10, cohort(first_ideoshock_1) control_cohort(never_ideoshock_1) covariates(`demecon') absorb(i.country_id i.year) vce(cluster e_regionpol)   
*outreg2 using mat.xlsx, excel
* We want the weighted coeficients
matrix B2 = e(b_iw)
matrix list B2
* Now we need to add the SE
mata st_matrix("A2",sqrt(diagonal(st_matrix("e(V_iw)"))))
matrix W2 = B2 \ A2'
matrix list W2
matrix rownames W2 = b se
* We need to create a matrix with the SE
matrix SE2 = W2["se",.]
matrix list SE2
*We add to our estored estimations the coeficients and the SE
estadd matrix B2
estadd matrix SE2
*We add a few 
estout using "Results\ES.xls", append  cells(B2(fmt(5)) SE2(par fmt(3)))
grstyle init 
 grstyle set color viridis, n(7) select(2):
 grstyle set color viridis, n(7) select(2): p#line p#bar p#fill
coefplot matrix(B2), se(SE2) keep(g*) vertical recast(line) note("{bf: Covariates}: Geopolitical region, population, GDP, PopDensity" "{bf: Number of obs}: 4,758") ///
levels(95 90) ciopts(lwidth(2.5 ..) lcolor(*.5 *.8)) ///
yline(0) ytitle(Effect on Liberal Democracy Index) ///
xline(9.5, lcolor(black) lpattern(solid))  xtitle(Years From the First Ideology Shock) ///
	coeflabels(g_10 = "-10" g_9 = "-9" g_8 = "-8" g_7 = "-7" g_6 = "-6" ///
				g_5 = "-5" g_4 = "-4" g_3 = "-3" g_2 = "-2" g_1 = "-1" ///
				g10 = "10" g9 = "9" g8 = "8" g7 = "7" g6 = "6" ///
				g5 = "5"   g4 = "4" g3 = "3" g2 = "2" g1 = "1" g0 = "0" )			
graph export "Results\ES_RE2.png", as(png) name("Graph") width(2000) replace
putexcel set "Results\ES_RE.xlsx", modify
putexcel a4="b2"
putexcel a5="se2"
putexcel b4=matrix(W2)
			
				
local polcris "e_regionpol PopulationtotalSPPOPTOTL GDPpercapitaconstant2015US Populationdensitypeoplepers e_pt_coup_attempts e_democracy_trans" 
eventstudyinteract libdemind100 g_* g0-g10, cohort(first_ideoshock_1) control_cohort(never_ideoshock_1) covariates(`polcris') absorb(i.country_id i.year) vce(cluster e_regionpol)   
ereturn list
*outreg2 using mat.xlsx, excel
* We want the weighted coeficients
matrix B3 = e(b_iw)
matrix list B3
* Now we need to add the SE
mata st_matrix("A3",sqrt(diagonal(st_matrix("e(V_iw)"))))
matrix W3 = B3 \ A3'
matrix list W3
matrix rownames W3 = b se
* We need to create a matrix with the SE
matrix SE3 = W3["se",.]
matrix list SE3
*We add to our estored estimations the coeficients and the SE
estadd matrix B3
estadd matrix SE3
*We add a few 
estout using "Results\ES.xls", append  cells(B3(fmt(5)) SE3(par fmt(3)))
grstyle init 
 grstyle set color viridis, n(7) select(3):
 grstyle set color viridis, n(7) select(3): p#line p#bar p#fill
coefplot matrix(B3), se(SE3) keep(g*) vertical recast(line) note("{bf: Covariates}: Geopolitical region, population, GDP, PopDensity" " number of coup attempts, safe democracy transition" "{bf: Number of obs}: 4,826") ///
levels(95 90) ciopts(lwidth(2.5 ..) lcolor(*.5 *.8)) ///
yline(0) ytitle(Effect on Liberal Democracy Index) ///
xline(9.5, lcolor(black) lpattern(solid))  xtitle(Years From the First Ideology Shock) ///
	coeflabels(g_10 = "-10" g_9 = "-9" g_8 = "-8" g_7 = "-7" g_6 = "-6" ///
				g_5 = "-5" g_4 = "-4" g_3 = "-3" g_2 = "-2" g_1 = "-1" ///
				g10 = "10" g9 = "9" g8 = "8" g7 = "7" g6 = "6" ///
				g5 = "5"   g4 = "4" g3 = "3" g2 = "2" g1 = "1" g0 = "0" )			
graph export "Results\ES_RE3.png", as(png) name("Graph") width(2000) replace
putexcel set "Results\ES_RE.xlsx", modify
putexcel a6="b3"
putexcel a7="se3"
putexcel b6=matrix(W3)

local ecocris "e_regionpol PopulationtotalSPPOPTOTL GDPpercapitaconstant2015US Populationdensitypeoplepers BankingCrisis CurrencyCrises InflationCrises"
eventstudyinteract libdemind100 g_* g0-g10, cohort(first_ideoshock_1) control_cohort(never_ideoshock_1) covariates(`ecocris') absorb(i.country_id i.year) vce(cluster e_regionpol)   
ereturn list
*outreg2 using mat.xlsx, excel
* We want the weighted coeficients
matrix B4 = e(b_iw)
matrix list B4
* Now we need to add the SE
mata st_matrix("A4",sqrt(diagonal(st_matrix("e(V_iw)"))))
matrix W4 = B4 \ A4'
matrix list W4
matrix rownames W4 = b se
* We need to create a matrix with the SE
matrix SE4 = W4["se",.]
matrix list SE4
*We add to our estored estimations the coeficients and the SE
estadd matrix B4
estadd matrix SE4
*We add a few 
estout using "Results\ES.xls", append  cells(B3(fmt(5)) SE3(par fmt(3)))
grstyle init 
 grstyle set color viridis, n(7) select(4):
 grstyle set color viridis, n(7) select(4): p#line p#bar p#fill
coefplot matrix(B4), se(SE4) keep(g*) vertical recast(line) note("{bf: Covariates}: Geopolitical region, population, GDP, PopDensity" " Banking Crises, Currency Crisis, Inflation Crisis" "{bf: Number of obs}: 1,563") ///
levels(95 90) ciopts(lwidth(2.5 ..) lcolor(*.5 *.8)) ///
yline(0) ytitle(Effect on Liberal Democracy Index) ///
xline(9.5, lcolor(black) lpattern(solid))  xtitle(Years From the First Ideology Shock) ///
	coeflabels(g_10 = "-10" g_9 = "-9" g_8 = "-8" g_7 = "-7" g_6 = "-6" ///
				g_5 = "-5" g_4 = "-4" g_3 = "-3" g_2 = "-2" g_1 = "-1" ///
				g10 = "10" g9 = "9" g8 = "8" g7 = "7" g6 = "6" ///
				g5 = "5"   g4 = "4" g3 = "3" g2 = "2" g1 = "1" g0 = "0" )			
graph export "Results\ES_RE4.png", as(png) name("Graph") width(2000) replace
putexcel set "Results\ES_RE.xlsx", modify
putexcel a8="b4"
putexcel a9="se4"
putexcel b8=matrix(W4)

/*
local educ "e_regionpol PopulationtotalSPPOPTOTL GDPpercapitaconstant2015US Populationdensitypeoplepers v2peedueq e_peaveduc"
eventstudyinteract libdemind100 g_* g0-g10, cohort(first_ideoshock_1) control_cohort(never_ideoshock_1) covariates(`educ') absorb(i.country_id i.year) vce(cluster e_regionpol)   
ereturn list
* We want the weighted coeficients
matrix B5 = e(b_iw)
matrix list B5
* Now we need to add the SE
mata st_matrix("A5",sqrt(diagonal(st_matrix("e(V_iw)"))))
matrix W5 = B5 \ A5'
matrix list W5
matrix rownames W5 = b se
* We need to create a matrix with the SE
matrix SE5 = W5["se",.]
matrix list SE5
*We add to our estored estimations the coeficients and the SE
estadd matrix B5
estadd matrix SE5
*We add a few 
estout using "Results\ES.xls", append  cells(B3(fmt(5)) SE3(par fmt(3)))
grstyle init 
 grstyle set color viridis, n(7) select(5):
 grstyle set color viridis, n(7) select(5): p#line p#bar p#fill
coefplot matrix(B5), se(SE5) keep(g*) vertical recast(line) note("{bf: Covariates}: Geopolitical region, population, GDP, PopDensity" " Education Pop 15+, educational equality" "{bf: Number of obs}: 3,892") ///
levels(95 90) ciopts(lwidth(2.5 ..) lcolor(*.5 *.8)) ///
yline(0) ytitle(Effect on Liberal Democracy Index) ///
xline(9.5, lcolor(black) lpattern(solid))  xtitle(Years From the First Ideology Shock) ///
	coeflabels(g_10 = "-10" g_9 = "-9" g_8 = "-8" g_7 = "-7" g_6 = "-6" ///
				g_5 = "-5" g_4 = "-4" g_3 = "-3" g_2 = "-2" g_1 = "-1" ///
				g10 = "10" g9 = "9" g8 = "8" g7 = "7" g6 = "6" ///
				g5 = "5"   g4 = "4" g3 = "3" g2 = "2" g1 = "1" g0 = "0" )			
graph export "Results\ES_RE5.png", as(png) name("Graph") width(2000) replace
putexcel set "Results\ES_RE.xlsx", modify
putexcel a10="b5"
putexcel a11="se5"
putexcel b10=matrix(W5)
*/
			
local all5 "e_regionpol PopulationtotalSPPOPTOTL GDPpercapitaconstant2015US Populationdensitypeoplepers e_pt_coup_attempts e_democracy_trans v2peedueq"
eventstudyinteract libdemind100 g_* g0-g10, cohort(first_ideoshock_1) control_cohort(never_ideoshock_1) covariates(`all5') absorb(i.country_id i.year) vce(cluster e_regionpol)   
*outreg2 using mat.xlsx, excel
ereturn list
* We want the weighted coeficients
matrix B6 = e(b_iw)
matrix list B6
* Now we need to add the SE
mata st_matrix("A6",sqrt(diagonal(st_matrix("e(V_iw)"))))
matrix W6 = B6 \ A6'
matrix list W6
matrix rownames W6 = b se
* We need to create a matrix with the SE
matrix SE6 = W6["se",.]
matrix list SE6
*We add to our estored estimations the coeficients and the SE
estadd matrix B6
estadd matrix SE6
*We add a few 
estout using "Results\ES.xls", append  cells(B3(fmt(5)) SE3(par fmt(3)))
 grstyle set color viridis, n(7) select(6):
 grstyle set color viridis, n(7) select(6): p#line p#bar p#fill
coefplot matrix(B6), se(SE5) keep(g*) vertical recast(line) note("{bf: Covariates}: Geopolitical region, population, GDP, PopDensity" " number of coup attempts, safe democracy transition, educational equality" "{bf: Number of obs}: 4,826") ///
levels(95 90) ciopts(lwidth(2.5 ..) lcolor(*.5 *.8)) ///
yline(0) ytitle(Effect on Liberal Democracy Index) ///
xline(9.5, lcolor(black) lpattern(solid))  xtitle(Years From the First Ideology Shock) ///
	coeflabels(g_10 = "-10" g_9 = "-9" g_8 = "-8" g_7 = "-7" g_6 = "-6" ///
				g_5 = "-5" g_4 = "-4" g_3 = "-3" g_2 = "-2" g_1 = "-1" ///
				g10 = "10" g9 = "9" g8 = "8" g7 = "7" g6 = "6" ///
				g5 = "5"   g4 = "4" g3 = "3" g2 = "2" g1 = "1" g0 = "0" )		
graph export "Results\ES_RE6.png", as(png) name("Graph") width(2000) replace
putexcel set "Results\ES_RE.xlsx", modify
putexcel a12="b6"
putexcel a13="se6"
putexcel b12=matrix(W6)				
					
				
  
use "Process\VDEM_Expanded_DB.dta", replace
*Per every country
*br year country_id EventDate_1
bysort country_id: egen first_ideoshock_1= min(EventDate_1)
bysort country_id: egen first_ideoshock_2= min(EventDate_2)
gen ry1 = year - first_ideoshock_1
gen never_ideoshock_1 = (first_ideoshock_1== .)
tab ry1
keep libdemind first_ideoshock_1 ry1 never_ideoshock_1 e_regionpol country_id year Populationdensitypeoplepers PopulationtotalSPPOPTOTL v2eltrnout e_peaveduc e_peedgini e_miurbpop e_mipopula e_wb_pop e_civil_war BankingCrisis CurrencyCrises InflationCrises e_gdppc
        forvalues k = 10(-1)1 {
           gen g_`k' = ry1 == -`k'
        }
        forvalues k = 0/10 {
             gen g`k' = ry1 == `k'
        }

gen libdemind100=100*libdemind		
*twoway (scatter libdemind100 ry1 if never_ideoshock_1==0)
*scatter libdemind100 ry1 if never_ideoshock_1==1
tab never_ideoshock_1, sum(libdemind100 )


****Educ & turnout		
eventstudyinteract libdemind100 g_* g0-g10, cohort(first_ideoshock_1) control_cohort(never_ideoshock_1) covariates(e_regionpol e_peaveduc e_peedgini v2eltrnout) absorb(i.country_id i.year) vce(cluster country_id)   
* e_miurbpop e_mipopula e_wb_pop e_civil_war BankingCrisis CurrencyCrises InflationCrises e_gdppc
return list 
ereturn list
* We want the weighted coeficients
matrix B = e(b_iw)
matrix list B
* Now we need to add the SE
mata st_matrix("A",sqrt(diagonal(st_matrix("e(V_iw)"))))
matrix W = B \ A'
matrix list W
matrix rownames W = b se
* We need to create a matrix with the SE
matrix SE = W["se",.]
matrix list SE
*We add to out estored estimations the coeficients and the SE
estadd matrix B
estadd matrix SE
* The Confidence interval
matrix define C = (e(b_iw) + e(SE) * invt(e(df_r), 0.025) \ ///
    e(b_iw) + e(SE)  * invt(e(df_r), 0.975))
matrix list C

coefplot matrix(B), keep(g*) vertical recast(line)  ///
se(SE) levels(95 90) ciopts(lwidth(2.5 ..) lcolor(*.2 *.5 *.8)) ///
yline(0) xline(10.5, lcolor(black) lpattern(solid)) ///
	coeflabels(g_10 = "-10" g_9 = "-9" g_8 = "-8" g_7 = "-7" g_6 = "-6" ///
				g_5 = "-5" g_4 = "-4" g_3 = "-3" g_2 = "-2" g_1 = "-1" ///
				g10 = "10" g9 = "9" g8 = "8" g7 = "7" g6 = "6" ///
				g5 = "5"   g4 = "4" g3 = "3" g2 = "2" g1 = "1" g0 = "0" )


****Crises
eventstudyinteract libdemind100 g_* g0-g10, cohort(first_ideoshock_1) control_cohort(never_ideoshock_1) covariates(e_regionpol BankingCrisis CurrencyCrises InflationCrises e_gdppc) absorb(i.country_id i.year) vce(cluster country_id)   
* e_miurbpop e_mipopula e_wb_pop e_civil_war 
return list 
ereturn list
* We want the weighted coeficients
matrix B = e(b_iw)
matrix list B
* Now we need to add the SE
mata st_matrix("A",sqrt(diagonal(st_matrix("e(V_iw)"))))
matrix W = B \ A'
matrix list W
matrix rownames W = b se
* We need to create a matrix with the SE
matrix SE = W["se",.]
matrix list SE
*We add to out estored estimations the coeficients and the SE
estadd matrix B
estadd matrix SE
* The Confidence interval
matrix define C = (e(b_iw) + e(SE) * invt(e(df_r), 0.025) \ ///
    e(b_iw) + e(SE)  * invt(e(df_r), 0.975))
matrix list C

coefplot matrix(B), keep(g*) vertical recast(line)  ///
se(SE) levels(95 90) ciopts(lwidth(2.5 ..) lcolor(*.2 *.5 *.8)) ///
yline(0) xline(10.5, lcolor(black) lpattern(solid)) ///
	coeflabels(g_10 = "-10" g_9 = "-9" g_8 = "-8" g_7 = "-7" g_6 = "-6" ///
				g_5 = "-5" g_4 = "-4" g_3 = "-3" g_2 = "-2" g_1 = "-1" ///
				g10 = "10" g9 = "9" g8 = "8" g7 = "7" g6 = "6" ///
				g5 = "5"   g4 = "4" g3 = "3" g2 = "2" g1 = "1" g0 = "0" )				
				
				
*** MERGING DS 3
******************************************************  
gen DSharp=(IdeoChange!=0)
gen  libdemind100=libdemind *100 
xtset country_id year
 xtreg libdemind100 idologysco
  est sto l0
  outreg2 using regressions.xls, excel  replace
 xtreg libdemind100 idologysco i.INCOME i.REGION
  est sto l1
  outreg2 using regressions.xls, excel  append 
 xtreg libdemind100 idologysco, fe
   est sto l2
  outreg2 using regressions.xls, excel  append 
 xtreg libdemind100 idologysco PopulationtotalSPPOPTOTL, fe
   est sto l3
  outreg2 using regressions.xls, excel  append 
 xtreg libdemind100 idologysco PopulationtotalSPPOPTOTL GDPconstant2015USNYGDP Inflationconsumerpricesannu Incomeshareheldbyhighest10, fe
   est sto l4
  outreg2 using regressions.xls, excel  append 
 xtreg libdemind100 idologysco PopulationtotalSPPOPTOTL GDPconstant2015USNYGDP Inflationconsumerpricesannu Incomeshareheldbyhighest10 exch_usd BankingCrisis SystemicCrisis CurrencyCrises InflationCrises, fe
   est sto l5
  outreg2 using regressions.xls, excel  append 
 xtreg libdemind100 idologysco DSharp PopulationtotalSPPOPTOTL GDPconstant2015USNYGDP Inflationconsumerpricesannu Incomeshareheldbyhighest10 exch_usd BankingCrisis SystemicCrisis CurrencyCrises InflationCrises, fe
   est sto l6
  outreg2 using regressions.xls, excel  append 
 
grstyle init
grstyle set color inferno, n(7) intensity(1.2): p# p#markfill p#bar p#markline p#barline p#lineplot
coefplot l*,  ///
	 keep(idologysco Incomeshareheldbyhighest10 ) 			 ///
      msymbol(d) mcolor(%70) mlcolor(*0.3) msize(1.5) 						  ///
	  	  coeflabels(idologysco = "Ideology Score"						///
			Incomeshareheldbyhighest10  = "Income Share Top 10%", wrap(10))			///
	  levels(99 95 90) ciopts(lwidth(1.6 1.5 1.3) lcolor(*.2 *.5 *.8))	xline(0) grid(none) xtitle("Changes in the Liberal Democray Index")    	  ///
	  legend(ring(1) pos(6) col(2) ///
				label(4 "A = Basic") label(8 "B = A + Income + Region") label(12 "C = Fixed Effects Time & Country")  ///
				label(16 "D = C + Population") label(20 "E = D + GDP + Inflation + %Top10")  			  ///
				label(24 "F = E + EXC Rate + Crisis") label(28 "G = F + Dummy")  region(color(none))) ///
	ysize(12) xsize(14)
 
 

***  DEED STUDY
******************************************************
use "Process\VDEM_Expanded_DB.dta", replace
drop _merge
 merge 1:1 country_name year using DEED
*We need to erase all the countries which do not appear in DEED
bysort country_name: egen delete=total(symptoms)
drop if delete==0
drop delete
*We erased 40 countries, and we have 139 countries left
*Per every country
*br year country_id EventDate_1
bysort country_id: egen first_ideoshock_1= min(EventDate_1)
bysort country_id: egen first_ideoshock_2= min(EventDate_2)
gen ry1 = year - first_ideoshock_1
gen never_ideoshock_1 = (first_ideoshock_1== .)
*Not all the countries with a DEED symptom experienced an ideological shock
*Now we need to think about the before
*br if first_ideoshock_1<1999
*We need to take off Belarus and Palestine due to their idological shocks were before 1999.
drop if country_name=="Belarus"
drop if country_name=="Palestine/West Bank"

replace RHor=0 if RHor==.
replace RHsymp_w=0 if RHsymp_w==.
replace RVer =0 if RVer ==.
replace RVsymp_w=0 if RVsymp_w==.

*br country_name year ry1 first_ideoshock_1

**Diferences-in-differences 
gen treated=(never_ideoshock_1==0)
tab treated, su(RHor)
tab time if treated==1, su(RHor)

tab treated, su(RVer)
tab time if treated==1, su(RVer)

tab treated time, m
gen time=(ry1>0)
 replace time = 0 if  time ==.
gen cont_time=ry1+31 
xtset country_id year 
gen did=treated*time 
/*
local demecon "PopulationtotalSPPOPTOTL GDPpercapitaconstant2015US Populationdensitypeoplepers"
reghdfe RHor did `demecon', absorb(country_name year) cluster( e_regionpol)
reghdfe RVer did `demecon', absorb(country_name year) cluster( e_regionpol)
reghdfe RHsymp_w did `demecon', absorb(country_name year) cluster( e_regionpol)
reghdfe RVsymp_w did `demecon', absorb(country_name year) cluster( e_regionpol)
*/
bysort time: su RHor if abs(ry1)<6 & ry1!=0
grstyle init
 grstyle set color viridis, n(7) select(1 3):
 grstyle set color viridis, n(7) select(1 3): p#line p#bar p#fill
graph bar RHor RVer if abs(ry1)<6 & ry1!=0, ///
 over(time, relab(1 "5 years before" 2 "5 years after") lab(labsize(medlarge))) ///
 ytitle("Number of Events per Year Country", size(medlarge)) yscale(r(0 0.8)) ylab(0(0.2)0.8, labsize(medlarge)) ///
 legend(ring(0) pos(11) label(1 "Horizontal") label(2 "Vertical") size(medlarge))
 
graph bar RHor if abs(ry1)<6, ///
over(ry1) ytitle("Mean of the Number of Reductions" "in Horizontal Accountability Events", size(*1.5))

graph bar RVer if abs(ry1)<6, ///
over(ry1) ytitle("Mean of the Number of Reductions" "in Horizontal Accountability Events", size(*1.5))

		*****************************************************
		 ***************************************************
		  **********#		FIGURES				#**********
		 ***************************************************
		*****************************************************


*** APPENDIX B
******************************************************
use "Process\VDEM_Expanded_DB.dta", replace
bysort country_id: egen first_ideoshock_1= min(EventDate_1)
bysort country_id: egen first_ideoshock_2= min(EventDate_2)
bysort country_id: egen first_ideoshock_11= min(EventDate_11)
bysort country_id: egen first_ideoshock_12= min(EventDate_12)
gen ry1 = year - first_ideoshock_1
gen never_ideoshock_1 = (first_ideoshock_1== .)
gen ry2 = year - first_ideoshock_2
gen never_ideoshock_2 = (first_ideoshock_2== .)
gen ry11 = year - first_ideoshock_11
gen never_ideoshock_11 = (first_ideoshock_11== .)
gen ry12 = year - first_ideoshock_12
gen never_ideoshock_12 = (first_ideoshock_12== .)
gen  libdemind100=libdemind *100 
keep libdemind100 ry* never_ideoshock_* country_name first_ideoshock_*
*We keep only the countries with ideological shocks
egen drop=rowtotal(never_ideoshock_1 never_ideoshock_2 never_ideoshock_11 never_ideoshock_12)
keep if drop<4
drop drop 
drop if country_name=="Palestine/West Bank" // We did not have all the data


drop if first_ideoshock_12==.
tostring first_ideoshock_12, replace
gen co_y = country_name + ", " + first_ideoshock_12
drop if ry12<-4 | ry12>4
tostring ry12, replace
replace ry12=subinstr(ry12,"-","_",1)
keep co_y libdemind100 ry12 
reshape wide libdemind100, i(co_y) j(ry12) string
gen diff_4yr=libdemind1004-libdemind100_4 if libdemind1004!=. & libdemind100_4!=.
gen diff_3yr=libdemind1003-libdemind100_3 if libdemind1003!=. & libdemind100_3!=.
gen diff_2yr=libdemind1002-libdemind100_2 if libdemind1002!=. & libdemind100_2!=.
keep co_y diff_*
